package com.cskaoyan.controller.wxcontroller;


import com.cskaoyan.bean.bo.CouponListBo;
import com.cskaoyan.bean.bo.wx.WxBasicQueryBo;
import com.cskaoyan.bean.bo.wx.WxCouponMylistBo;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.wx.CartIndexVo;
import com.cskaoyan.bean.vo.wx.WxBaseRespVo;
import com.cskaoyan.bean.vo.wx.WxCouponSelectListVo;
import com.cskaoyan.bean.vo.wx.WxMyCouponMylistVo;
import com.cskaoyan.service.CartService;
import com.cskaoyan.service.PromotionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author: lsy
 * @class: CouponController
 */
@RestController("wxCouponController")
@RequestMapping("wx/coupon")
public class CouponController {

    @Autowired
    PromotionService promotionService;
    @Autowired
    CartService cartService;




    @GetMapping("mylist")
    public BaseRespVo mylist(WxCouponMylistBo wxCouponMylistBo) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user == null) {
            return BaseRespVo.fail("请登录");
        }
        WxMyCouponMylistVo wxMyCouponMylistVo = promotionService.queryWxCouponsByUserId(wxCouponMylistBo, user.getId());
        return BaseRespVo.ok(wxMyCouponMylistVo);
    }

    @GetMapping("list")
    public BaseRespVo list(WxBasicQueryBo wxBasicQueryBo) {
        WxBaseRespVo<Coupon> wxBaseRespVo = promotionService.queryCouponsByPage(wxBasicQueryBo);
        return BaseRespVo.ok(wxBaseRespVo);
    }

    @PostMapping("exchange")
    public BaseRespVo exchange(@RequestBody Map<String, String> codeMap) {
        String code = codeMap.get("code");
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user == null) {
            return BaseRespVo.fail("请登录");
        }
        int success = promotionService.addWxCouponByCode(code, user.getId());
        if (success == 1) {
            return BaseRespVo.ok("兑换成功");
        }
        if (success == 2) {
            return BaseRespVo.fail("已兑换");
        }
        return BaseRespVo.fail("输入兑换码错误");
    }

    /**
     * @author: lsy
     * @title: receive
     * @description: 如果用户没有这个id的优惠券，可以领取一个，不然不能领取
     * @param: [couponId]
     * @return: com.cskaoyan.bean.vo.WxBaseRespVo
     */
    @PostMapping("receive")
    public BaseRespVo receive(@RequestBody Map<String, Integer> couponMap) {
        int couponId = couponMap.get("couponId");
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user == null) {
            return BaseRespVo.fail("请登录");
        }
        CouponUser couponUser = promotionService.queryCouponUserByCouponIdAndUserId(couponId, user.getId());
        if (couponUser != null) {
            return BaseRespVo.fail("优惠券已经领取过");
        }
        Coupon coupon = promotionService.queryCoupon(couponId);
        promotionService.addCouponUserByUserIdAndCoupon(coupon, user.getId());
        return BaseRespVo.ok();
    }

    /**
     * <<<<<<< HEAD
     *
     * @author: lsy
     * @title: selectList
     * @description: 根据购物车id和团购规则id查询用户拥有的优惠券信息
     * @param: [cartId, grouponRulesId]
     * @return: com.cskaoyan.bean.vo.BaseRespVo
     */
    @GetMapping("selectlist")
    public BaseRespVo selectlist(int cartId, int grouponRulesId) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user == null) {
            return BaseRespVo.fail("请登录");
        }
//        List<Cart> cartList = cartService.queryCartById(cartId);
        Integer userId = user.getId();
        CartIndexVo cartIndexVo = cartService.queryCartIndex(userId, cartId, true);//获取当前订单的所有信息
//        GrouponRules grouponRules = promotionService.querygrouponRulesById(grouponRulesId);
        List<CouponUser> couponUserList = promotionService.queryCouponUserByUserId(userId);//获取所有优惠券列表

        List<Coupon> availableCouponList = cartService.queryAvailableCouponList(user.getId(), cartIndexVo, cartId);//获取所有该订单可用优惠券列表
        ArrayList<Integer> availableCouponIds = new ArrayList<>();//可用优惠券id的集合
        for (Coupon coupon : availableCouponList) {
            availableCouponIds.add(coupon.getId());
        }

        ArrayList<WxCouponSelectListVo> wxCouponSelectListVos = new ArrayList<>();
        for (CouponUser couponUser : couponUserList) {
            Integer couponId = couponUser.getCouponId();
            Coupon coupon = promotionService.queryCouponById(couponId);


            WxCouponSelectListVo wxCouponSelectListVo = new WxCouponSelectListVo();
            // 无限制
            wxCouponSelectListVo.setDesc(coupon.getDesc());
            // 抵扣金额
            wxCouponSelectListVo.setDiscount(coupon.getDiscount());
            // 优惠券id
            wxCouponSelectListVo.setId(coupon.getId());
            // 最低满多少可以用
            wxCouponSelectListVo.setMin(coupon.getMin());
            // 优惠券名称
            wxCouponSelectListVo.setName(coupon.getName());

            // 优惠券开始结束时间
            if (coupon.getTimeType() == 1) {
                wxCouponSelectListVo.setStartTime(coupon.getStartTime());
                wxCouponSelectListVo.setEndTime(coupon.getEndTime());
            } else {
                // 根据days和couponUser的添加时间addTime确定
                wxCouponSelectListVo.setStartTime(couponUser.getAddTime());
                long millTime = couponUser.getAddTime().getTime() + coupon.getDays() * 24 * 60 * 60 * 1000;
                wxCouponSelectListVo.setEndTime(new Date(millTime));
            }



            Date date = new Date();
//            if (date.getTime() < wxCouponSelectListVo.getStartTime().getTime() || date.getTime() > wxCouponSelectListVo.getEndTime().getTime()) {
//                wxCouponSelectListVo.setCanSelect(false);
//                wxCouponSelectListVo.setCanNotSelect(true);
//            } else {
//                wxCouponSelectListVo.setCanSelect(true);
//                wxCouponSelectListVo.setCanNotSelect(false);
//            }
              if (!availableCouponIds.contains(coupon.getId())){
                  wxCouponSelectListVo.setCanSelect(false);
                  wxCouponSelectListVo.setCanNotSelect(true);
              }else{
                  wxCouponSelectListVo.setCanSelect(true);
                  wxCouponSelectListVo.setCanNotSelect(false);
              }


            // 左上角
            wxCouponSelectListVo.setTag(coupon.getTag());

            if ("全场通用".equals(coupon.getDesc())) {
                wxCouponSelectListVo.setPic("/static/images/全场通用.svg");
            } else if ("指定分类".equals(coupon.getDesc())) {
                wxCouponSelectListVo.setPic("/static/images/指定分类.svg");
            } else if ("指定商品".equals(coupon.getDesc())) {
                wxCouponSelectListVo.setPic("/static/images/指定商品.svg");
            }
            wxCouponSelectListVos.sort(new Comparator<WxCouponSelectListVo>() {
                @Override
                public int compare(WxCouponSelectListVo o1, WxCouponSelectListVo o2) {
                    // 从大到小排序
                    return -o1.getDiscount().compareTo(o2.getDiscount());
                }
            });

            wxCouponSelectListVos.add(wxCouponSelectListVo);


        }

        return BaseRespVo.ok(wxCouponSelectListVos);
    }

//    /**
//     * 根据用户id，购物车id查询当前订单可用优惠券
//     *
//     * @param cartId
//     * @param grouponRulesId
//     * @return
//     */
//    @GetMapping("selectlist")
//    public BaseRespVo selectList1(Integer cartId, Integer grouponRulesId) {
//        //cartId不为0，表示fastadd直接购买的情况
//        //cart为0，表示购物车中下单的情况
////        Subject subject = SecurityUtils.getSubject();
////        User user = (User) subject.getPrincipal();
////        if (user == null) {
////            return BaseRespVo.fail("请登录");
////        }
//        //查询购物车中选中商品列表
//        CartIndexVo cartChecked = cartService.queryCartIndex(1, cartId, true);
//        List<Coupon> couponList = cartService.queryAvailableCouponList(1, cartChecked, cartId);
//        //前端需求的数据格式没有显示团购优惠信息，grouponRulesId这里就不做处理了，在CartService中另写接口处理
//        return BaseRespVo.ok(couponList);
//
//    }
}
